package net.maku.kyy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fhs.common.utils.StringUtil;
import io.micrometer.common.util.StringUtils;
import lombok.AllArgsConstructor;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.kyy.convert.KyyGameConvert;
import net.maku.kyy.entity.KyyGameEntity;
import net.maku.kyy.query.KyyGameQuery;
import net.maku.kyy.vo.KyyGameVO;
import net.maku.kyy.dao.KyyGameDao;
import net.maku.kyy.service.KyyGameService;
import com.fhs.trans.service.impl.TransService;
import net.maku.framework.common.utils.ExcelUtils;
import net.maku.kyy.vo.KyyGameExcelVO;
import net.maku.framework.common.excel.ExcelFinishCallBack;
import org.springframework.web.multipart.MultipartFile;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 快应用
 *
 * @author MAKU babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@Service
@AllArgsConstructor
public class KyyGameServiceImpl extends BaseServiceImpl<KyyGameDao, KyyGameEntity> implements KyyGameService {
    private final TransService transService;

    @Override
    public PageResult<KyyGameVO> page(KyyGameQuery query) {
        IPage<KyyGameEntity> page = baseMapper.selectPage(getPage(query), getWrapper(query));

        return new PageResult<>(KyyGameConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }


    private LambdaQueryWrapper<KyyGameEntity> getWrapper(KyyGameQuery query) {
        LambdaQueryWrapper<KyyGameEntity> wrapper = Wrappers.lambdaQuery();

        if ("true".equals(query.getSearchAll())) {
            wrapper.like(KyyGameEntity::getAppname, query.getAppname())
                    .or(introWrapper -> introWrapper.like(KyyGameEntity::getBriefIntro, query.getBriefIntro()));
        }else{
            //游戏搜索
            wrapper.like(StringUtils.isNotEmpty(query.getAppname()), KyyGameEntity::getAppname, query.getAppname());
            //简介搜索
            wrapper.like(StringUtils.isNotEmpty(query.getBriefIntro()), KyyGameEntity::getBriefIntro, query.getBriefIntro());
        }


        //2级标签名搜索
        wrapper.like(StringUtils.isNotEmpty(query.getCategory2Name()), KyyGameEntity::getCategory2Name, query.getCategory2Name());
        //3级标签名搜索
        wrapper.like(StringUtils.isNotEmpty(query.getCategory3Name()), KyyGameEntity::getCategory3Name, query.getCategory3Name());
        //2级标签id搜索
        wrapper.like(StringUtils.isNotEmpty(query.getCategory2Id()), KyyGameEntity::getCategory2Id, query.getCategory2Id());
        //3级标签id搜索
        wrapper.like(StringUtils.isNotEmpty(query.getCategory3Id()), KyyGameEntity::getCategory3Id, query.getCategory3Id());
        //打乱顺序，猜你喜欢
        if ("true".equals(query.getRandomGame())) {
            wrapper.last("ORDER BY RAND()");
        }
        //banner不为空
        if ("true".equals(query.getBannerGame())) {
            wrapper.isNotNull(KyyGameEntity::getBanner);
            wrapper.ne(KyyGameEntity::getBanner, "");
        }
        //热度排名
        if ("true".equals(query.getHot())) {
            wrapper.orderByDesc(StringUtils.isNotEmpty(query.getHot()), KyyGameEntity::getClickCount);
        }
        //畅销排名
        if ("true".equals(query.getOpenHot())) {
            wrapper.orderByDesc(StringUtils.isNotEmpty(query.getOpenHot()), KyyGameEntity::getOpenCount);
        }
        return wrapper;
    }


    @Override
    public KyyGameVO get(Long id) {
        KyyGameEntity entity = baseMapper.selectById(id);
        KyyGameVO vo = KyyGameConvert.INSTANCE.convert(entity);

        return vo;
    }

    @Override
    public KyyGameVO getByAppid(String appid) {
        QueryWrapper<KyyGameEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("appid", appid);
        KyyGameEntity entity = baseMapper.selectOne(queryWrapper);
        if (entity != null) {
            return KyyGameConvert.INSTANCE.convert(entity);
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> getCategory2Name() {
        LambdaQueryWrapper<KyyGameEntity> wrapper = Wrappers.lambdaQuery();
        Map<String, Map<String, Object>> uniqueMap = new HashMap<>();
        baseMapper.selectList(wrapper).forEach(entity -> {
            String id = String.valueOf(entity.getCategory2Id());  // 获取实体的id并转换为字符串类型
            if (!uniqueMap.containsKey(id)) {  // 以id作为键来判断是否已存在
                uniqueMap.put(id, Map.<String, Object>of(
                        "category2Id", entity.getCategory2Id(),
                        "category2Name", entity.getCategory2Name()
                ));
            }
        });
        return new ArrayList<>(uniqueMap.values());
    }

    @Override
    public List<Map<String, Object>> getCategory3Name(KyyGameQuery query) {
        LambdaQueryWrapper<KyyGameEntity> wrapper = Wrappers.lambdaQuery();
        // 热度排名
        wrapper.like(StringUtils.isNotEmpty(query.getCategory3Name()), KyyGameEntity::getCategory3Name, query.getCategory3Name());

        Map<String, Map<String, Object>> uniqueMap = new HashMap<>();
        baseMapper.selectList(wrapper).forEach(entity -> {
            String key = entity.getCategory3Name() + "_" + entity.getCategory3Id();
            if (!uniqueMap.containsKey(key)) {
                uniqueMap.put(key, Map.<String, Object>of(
                        "category3Id", entity.getCategory3Id(),
                        "category3Name", entity.getCategory3Name()
                ));
            }
        });
        return new ArrayList<>(uniqueMap.values());
    }

    @Override
    public List<KyyGameEntity> getAll() {
        QueryWrapper<KyyGameEntity> queryWrapper = new QueryWrapper<>();
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(KyyGameVO vo) {
        KyyGameEntity entity = KyyGameConvert.INSTANCE.convert(vo);

        baseMapper.insert(entity);


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(KyyGameVO vo) {
        KyyGameEntity entity = KyyGameConvert.INSTANCE.convert(vo);
        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);

    }


    @Override
    public void export() {
        List<KyyGameExcelVO> excelList = KyyGameConvert.INSTANCE.convertExcelList(list());
        transService.transBatch(excelList);
        ExcelUtils.excelExport(KyyGameExcelVO.class, "快应用", null, excelList);
    }

}